using B.S.XZYData.Api.Wrter.Application.Command.ProductionStatistics;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;
using System.Linq;

namespace B.S.XZYData.Api.Wrter.Application.Handler.ProductionStatistics
{
    /// <summary>
    /// 导出产量统计处理器
    /// </summary>
    public class ExportProductionStatisticsHandler : IRequestHandler<ExportProductionStatisticsCommand, ApiResult<byte[]>>
    {
        private readonly IBaseRepository<Domain.ZSHH.ProductionStatistics> _productionStatisticsRepo;
        private readonly ILogger<ExportProductionStatisticsHandler> _logger;

        public ExportProductionStatisticsHandler(
            IBaseRepository<Domain.ZSHH.ProductionStatistics> productionStatisticsRepo,
            ILogger<ExportProductionStatisticsHandler> logger)
        {
            _productionStatisticsRepo = productionStatisticsRepo;
            _logger = logger;
        }

        public async Task<ApiResult<byte[]>> Handle(ExportProductionStatisticsCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<byte[]>();
            try
            {
                // 构建查询条件
                var query = _productionStatisticsRepo.GetAll()
                    .Where(x => !x.IsDeleted);

                // 应用筛选条件
                query = ApplyFilters(query, request);

                // 应用排序
                query = ApplySorting(query, request.SortField, request.SortDirection);

                // 获取所有数据
                var productionStatisticsList = await query.ToListAsync();

                if (!productionStatisticsList.Any())
                {
                    res.Msg = "没有找到符合条件的产量统计数据";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                // 导出到Excel
                var excelBytes = await ExportToExcel(productionStatisticsList);

                res.Data = excelBytes;
                res.Code = ApiEnum.Success;
                res.Msg = "导出成功";
                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"导出产量统计异常：{ex.Message}");
                res.Msg = "导出产量统计异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }

        /// <summary>
        /// 应用筛选条件
        /// </summary>
        private ISugarQueryable<Domain.ZSHH.ProductionStatistics> ApplyFilters(
            ISugarQueryable<Domain.ZSHH.ProductionStatistics> query,
            ExportProductionStatisticsCommand request)
        {
            // 报工日期范围筛选
            if (request.ReportingDateStart.HasValue)
            {
                query = query.Where(x => x.ReportingDate >= request.ReportingDateStart.Value);
            }
            if (request.ReportingDateEnd.HasValue)
            {
                query = query.Where(x => x.ReportingDate <= request.ReportingDateEnd.Value);
            }

            // 工单计划数范围筛选
            if (request.WorkOrderPlanCountMin.HasValue)
            {
                query = query.Where(x => x.WorkOrderPlanCount >= request.WorkOrderPlanCountMin.Value);
            }
            if (request.WorkOrderPlanCountMax.HasValue)
            {
                query = query.Where(x => x.WorkOrderPlanCount <= request.WorkOrderPlanCountMax.Value);
            }

            // 产品名称筛选
            if (!string.IsNullOrEmpty(request.ProductName))
            {
                query = query.Where(x => x.ProductName.Contains(request.ProductName));
            }

            // 产品编号筛选
            if (!string.IsNullOrEmpty(request.ProductNumber))
            {
                query = query.Where(x => x.ProductNumber.Contains(request.ProductNumber));
            }

            // 产品规格筛选
            if (!string.IsNullOrEmpty(request.ProductSpecification))
            {
                query = query.Where(x => x.ProductSpecification.Contains(request.ProductSpecification));
            }

            // 单位筛选
            if (!string.IsNullOrEmpty(request.Unit))
            {
                query = query.Where(x => x.Unit.Contains(request.Unit));
            }

            // 数量范围筛选
            if (request.QuantityMin.HasValue)
            {
                query = query.Where(x => x.Quantity >= request.QuantityMin.Value);
            }
            if (request.QuantityMax.HasValue)
            {
                query = query.Where(x => x.Quantity <= request.QuantityMax.Value);
            }

            return query;
        }

        /// <summary>
        /// 应用排序
        /// </summary>
        private ISugarQueryable<Domain.ZSHH.ProductionStatistics> ApplySorting(
            ISugarQueryable<Domain.ZSHH.ProductionStatistics> query,
            string sortField,
            string sortDirection)
        {
            switch (sortField.ToLower())
            {
                case "reportingdate":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.ReportingDate)
                        : query.OrderByDescending(x => x.ReportingDate);

                case "workorderplancount":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.WorkOrderPlanCount)
                        : query.OrderByDescending(x => x.WorkOrderPlanCount);

                default:
                    // 默认按Id倒序
                    return query.OrderByDescending(x => x.Id);
            }
        }

        /// <summary>
        /// 导出到Excel
        /// </summary>
        private async System.Threading.Tasks.Task<byte[]> ExportToExcel(List<Domain.ZSHH.ProductionStatistics> productionStatisticsList)
        {
            using (var workbook = new XSSFWorkbook())
            {
                // 创建产量统计工作表
                var sheet = workbook.CreateSheet("产量统计");
                CreateSheet(sheet, productionStatisticsList);

                // 导出到内存流
                using (var ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    return ms.ToArray();
                }
            }
        }

        /// <summary>
        /// 创建工作表
        /// </summary>
        private void CreateSheet(ISheet sheet, List<Domain.ZSHH.ProductionStatistics> productionStatisticsList)
        {
            // 创建标题行样式
            var headerStyle = CreateHeaderStyle(sheet.Workbook);

            // 创建标题行
            var headerRow = sheet.CreateRow(0);
            var headers = new[] { "报工日期", "工单计划数", "产品名称", "产品编号", "产品规格", "单位", "数量", "创建时间", "创建人" };

            for (int i = 0; i < headers.Length; i++)
            {
                var cell = headerRow.CreateCell(i);
                cell.SetCellValue(headers[i]);
                cell.CellStyle = headerStyle;
                sheet.SetColumnWidth(i, 15 * 256); // 设置列宽
            }

            // 创建数据行
            for (int rowIndex = 0; rowIndex < productionStatisticsList.Count; rowIndex++)
            {
                var productionStatistics = productionStatisticsList[rowIndex];
                var dataRow = sheet.CreateRow(rowIndex + 1);

                dataRow.CreateCell(0).SetCellValue(productionStatistics.ReportingDate.ToString("yyyy-MM-dd"));
                dataRow.CreateCell(1).SetCellValue(productionStatistics.WorkOrderPlanCount ?? 0);
                dataRow.CreateCell(2).SetCellValue(productionStatistics.ProductName ?? "");
                dataRow.CreateCell(3).SetCellValue(productionStatistics.ProductNumber ?? "");
                dataRow.CreateCell(4).SetCellValue(productionStatistics.ProductSpecification ?? "");
                dataRow.CreateCell(5).SetCellValue(productionStatistics.Unit ?? "");
                dataRow.CreateCell(6).SetCellValue(productionStatistics.Quantity);
                dataRow.CreateCell(7).SetCellValue(productionStatistics.CreatorDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "");
                dataRow.CreateCell(8).SetCellValue(productionStatistics.Creator ?? "");
            }
        }

        /// <summary>
        /// 创建标题行样式
        /// </summary>
        private ICellStyle CreateHeaderStyle(IWorkbook workbook)
        {
            var headerStyle = workbook.CreateCellStyle();
            var headerFont = workbook.CreateFont();
            headerFont.IsBold = true;
            headerFont.FontHeightInPoints = 12;
            headerStyle.SetFont(headerFont);
            headerStyle.Alignment = HorizontalAlignment.Center;
            headerStyle.VerticalAlignment = VerticalAlignment.Center;
            headerStyle.BorderTop = BorderStyle.Thin;
            headerStyle.BorderBottom = BorderStyle.Thin;
            headerStyle.BorderLeft = BorderStyle.Thin;
            headerStyle.BorderRight = BorderStyle.Thin;
            return headerStyle;
        }
    }
} 